<template>
    <div v-if="systemSettings.openTagView">
        <el-scrollbar
            ref="scrollbar"
            max-height="38px"
            class="tags-container"
            :style="{width: 'calc(100vw - ' + (sidebarWidth + 30) + 'px)'}"
            :class="systemSettings.fixedTagView ? 'tags-view-fixed' : ''"
            @mouseover="addWheel"
            @mouseout="removeWheel"
        >
            <el-tag
                v-for="i in tags"
                :key="i.name"
                :closable="i.name !== 'home'"
                :type="i.type ? i.type : 'info'"
                style="margin-right: 10px; padding: 0 15px; cursor: pointer"
                disable-transitions
                @click="selectTag(i)"
                @close="closeCurrent(i)"
                @contextmenu="showMenu(i, $event)"
            >
                {{ subName('sidebar.' + i.name, i.name) }}
            </el-tag>
        </el-scrollbar>
        <div
            v-show="menuVisible"
            id="contextmenu"
            class="menu"
        >
            <div
                v-if="showRefresh"
                class="contextmenu__item"
                @click="refresh"
            >
                刷新
            </div>
            <div
                v-if="showClose"
                class="contextmenu__item"
                @click="closeTag"
            >
                关闭
            </div>
            <div
                class="contextmenu__item"
                @click="closeOtherTag"
            >
                关闭其它
            </div>
        </div>
        <!-- 占位 -->
        <div
            v-if="systemSettings.fixedTagView"
            class="tag-view-fixed-symbolic"
        />
        <!-- 占位 -->
        <div
            v-else
            class="tag-view-symbolic"
        />
    </div>
    <!-- 占位 -->
    <div
        v-else
        class="tag-view-symbolic"
    />
</template>

<script>
import { mapState } from 'vuex'
export default {
    name: "Index",
    data() {
        return {
            scrolling: 0,
            prevScroll: 0,
            showClose: false,
            showRefresh: false,
            menuVisible: false,
            currentSelected: null,
            contextMenuSelected: null
        }
    },
    computed: {
        ...mapState({
            // 标签
            tags: state => state.tagViews,
            // 左侧菜单宽度
            sidebarWidth: state => state.sidebarWidth,
            // 系统设置
            systemSettings: state => state.systemSettings,
        })
    },
    watch: {
        $route() {
            this.changeTag();
        }
    },
    mounted() {
        this.changeTag();
    },
    methods: {
        addWheel() {
            //获取兼容事件
            let mouseWheel = (/Firefox/i.test(navigator.userAgent))?"DOMMouseScroll": "mousewheel";
            // 添加滚动监听
            window.addEventListener(mouseWheel, this.handleScroll,true)
        },
        removeWheel() {
            //获取兼容事件
            let mouseWheel = (/Firefox/i.test(navigator.userAgent))? "DOMMouseScroll" : "mousewheel";
            //  离开页面清除（移除）滚轮滚动事件
            window.removeEventListener(mouseWheel, this.handleScroll, true);
        },
        // 关闭当前标签
        closeCurrent: function (tag) {
            let indexOf = this.tags.indexOf(tag);
            const currentIndex = this.tags.indexOf(this.currentSelected);
            if (indexOf === currentIndex) {
                this.selectTag(this.tags[indexOf - 1])
            }
            if (indexOf > -1) {
                this.tags.splice(indexOf, 1);
            }
        },
        // 选择标签
        selectTag(tag) {
            this.tags.forEach(e => e.type = null);
            tag.type = 'success';
            this.$router.push(tag.path);
            this.currentSelected = tag;
        },
        // 滚轮滚动处理
        handleScroll(e) {
            if (!this.$refs.scrollbar) {
                return
            }
            let scrollWidth = this.$refs.scrollbar.$el.childNodes[0].scrollLeft;
            this.scrolling += e.deltaY * 1.5;
            // 手动设置滑轮滚动时，滚动条跟着滚动
            this.$refs.scrollbar.setScrollLeft(this.scrolling);
            this.prevScroll = scrollWidth;
            if (this.prevScroll < this.scrolling) {
                this.scrolling = this.prevScroll;
            } else if (this.scrolling < 0) {
                this.scrolling = 0;
            }
        },
        changeTag() {
            const current = this.$router.currentRoute.value;
            const name = current.meta.name;
            const exists = this.tags.filter(e => e.name === name);
            if (!exists || exists.length === 0) {
                const tag = {
                    name,
                    type: 'info',
                    path: current.path
                };
                // 不存在
                this.tags.push(tag);
                this.selectTag(tag);
            } else {
                this.selectTag(exists[0]);
            }
        },
        refresh() {
            this.$store.commit('reloadMainPage');
        },
        closeTag() {
            this.closeCurrent(this.contextMenuSelected);
        },
        closeOtherTag() {
            let temp = [];
            if (this.contextMenuSelected.path !== '/') {
                temp = [this.tags[0], this.contextMenuSelected];
            } else {
                temp = [this.tags[0]];
            }
            this.tags.splice(0, this.tags.length);
            temp.forEach(e => {
                this.tags.push(e);
            });
            this.selectTag(this.contextMenuSelected);
        },
        subName(i18nKey, val) {
            return this.$t(i18nKey) === i18nKey ? val : this.$t(i18nKey);
        },
        showMenu(item, ev) {
            this.menuVisible = false; // 先把模态框关死，目的是 第二次或者第n次右键鼠标的时候 它默认的是true
            this.menuVisible = true; // 显示模态窗口，跳出自定义菜单栏
            ev.preventDefault(); //关闭浏览器右键默认事件
            let menu = document.querySelector('.menu');
            this.styleMenu(menu, ev);
            this.showClose = item.path !== '/';
            this.showRefresh = item.type === 'success';
            this.contextMenuSelected = item;
        },
        foo() {
            // 取消鼠标监听事件 菜单栏
            this.menuVisible = false;
            document.removeEventListener('click', this.foo); // 关掉监听，
        },
        styleMenu(menu, ev) {
            menu.style.left = ev.clientX - this.sidebarWidth + 'px';
            menu.style.top = ev.clientY + 20 + 'px';
            // 给整个document新增监听鼠标事件，点击任何位置执行foo方法
            document.addEventListener('click', this.foo);
        },
    }

}
</script>

<style scoped>
    .tags-container {
        height: 38px;
        margin-top: 1px;
        line-height: 38px;
        padding-left: 30px;
        padding-right: 30px;
        white-space: nowrap;
        padding-bottom: 3px;
        display: inline-flex;
        background-color: white;
        border-bottom: 1px solid #EBEEF5;
    }
    .tags-view-fixed {
        top: 56px;
        z-index: 2;
        position: fixed;
    }
    .tag-view-symbolic {
        height: 15px;
    }
    .tag-view-fixed-symbolic {
        height: 58px;
    }
    .tag-view-close-symbolic {
        height: 12px;
    }
    .contextmenu__item {
        display: block;
        line-height: 34px;
        text-align: center;
    }
    .contextmenu__item:not(:last-child) {
        border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    }
    .menu {
        position: absolute;
        background-color: #fff;
        width: 100px;
        /*height: 106px;*/
        font-size: 12px;
        color: #444040;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        border-radius: 3px;
        border: 1px solid rgba(0, 0, 0, 0.15);
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
        white-space: nowrap;
        z-index: 20000;
    }
    .contextmenu__item:hover {
        cursor: pointer;
        background: #66b1ff;
        border-color: #66b1ff;
        color: #fff;
    }
</style>
